<?php
/**
 * Repository trida s rozsirujicimi operacemi pro entitu Repository.
 * 
 * @author David Dusek 
 */

namespace CMS\User\Models;

use Doctrine\ORM\EntityRepository;

class ResourceRepository extends EntityRepository {    
    /**
     * Vyber zdroju pro zadany modul.
     * @param String $module Nazev modulu
     * @return array 
     */
    public function getExistingResources($module) {
        $qb = $this->_em->createQueryBuilder();
        $query = $qb->select('r')
                    ->from("\CMS\User\Models\Resource", 'r')
                    ->where("r.module = '$module'")
                    ->getQuery();
        return $query->getResult();
    }
    
    /**
     * Vyber nazvu modulu ze zdroju.
     * @return array Pole obsahuje nazvy modulu, kde kazdy je prave jednou. 
     */
    public function getModuleList() {
        $qb = $this->_em->createQueryBuilder();
        $query = $qb->select("r.module")
                    ->from("\CMS\User\Models\Resource", 'r')
                    ->distinct()
                    ->getQuery();
        $modules = $query->getResult();
        
        $res = array();
        foreach ($modules as $module) {
            $res[] = $module["module"];
        }
        
        return $res;
    }
    
    /**
     * Smazani zdroju, ktere maji atribut module nastaveny na jednu z hodnot v
     * poli moduleList.
     * @param array $moduleList Nazvy modulu pro ktere se maji zdroje smazat.
     */
    public function removeMissingModules($moduleList) {
        $in = "";
        if (is_array($moduleList) && count($moduleList) > 0) {
            foreach ($moduleList as $removeModule) {
                $in .= "'$removeModule'," ;
            }
            $in = substr($in, 0, -1);
            
            $qb = $this->_em->createQueryBuilder();
            $query = $qb->select('r')
                        ->from("\CMS\User\Models\Resource", "r")
                        ->where($qb->expr()->in("r.module", $in))->getQuery();
            $results = $query->getResult();
            
            foreach ($results as $resource) {
                $this->_em->remove($resource);
            }
            $this->_em->flush();
        }
    }
}
